import 'dart:convert';

import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter_taotaoshipin/app/app_controller.dart';
import 'package:flutter_taotaoshipin/http/dao/app_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/goods_dao.dart';
import 'package:flutter_taotaoshipin/http/dao/userinfo_dao.dart';
import 'package:flutter_taotaoshipin/model/goods_list_entity.dart';
import 'package:flutter_taotaoshipin/pages/drama/drama_routes.dart';
import 'package:flutter_taotaoshipin/pages/purchase/purchase_type.dart';
import 'package:flutter_taotaoshipin/pages/purchase/subscription/open/subscription_open_controller.dart';
import 'package:flutter_taotaoshipin/pages/purchase/subscription/open/subscription_open_page.dart';
import 'package:flutter_taotaoshipin/pages/report/report_page.dart';
import 'package:flutter_taotaoshipin/pages/root_tab/root_tab_state.dart';
import 'package:flutter_taotaoshipin/util/format_utils.dart';
import 'package:flutter_taotaoshipin/value/global_config.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

class RootTabController extends GetxController {
  var state = RootTabState();

  GoodsListEntity? vip;

  @override
  void onInit() {
    _loadAppConfig().then((_) {
      // 自动播放
      autoPlay();
      // 显示vip
      showVip();
      // 显示举报页面
      showReportView();
    });
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  ///切换tab
  void switchTap(int index) {
    state.selectedIndex.value = index;
    state.pageController.jumpToPage(index);
  }

  void autoPlay() {
    // 审核状态
    if (GlobalConfig.isReview == 1) {
      return;
    }
    // 进入播放页
    AppController appController = Get.find();
    if (appController.userLoginPlay?.auto == true) {
      if (GlobalConfig.forceDisplayPromotion == 1) {
        // 跳转视频详情页
        Get.toNamed(DramaRoutes.detail, arguments: {
          'id': appController.userLoginPlay?.dramaId,
          'title': '',
          'sort': appController.userLoginPlay?.sort,
        });
      } else if (!DateUtil.isToday(
          appController.appProfile.openAutoPlayTimestamp!)) {
        // 记录上次打开的时间
        appController.appProfile.openAutoPlayTimestamp =
            DateTime.now().millisecondsSinceEpoch;
        appController.updateAppProfile(appController.appProfile);
        // 跳转视频详情页
        Get.toNamed(DramaRoutes.detail, arguments: {
          'id': appController.userLoginPlay?.dramaId,
          'title': '',
          'sort': appController.userLoginPlay?.sort,
        });
      }
    }
  }

  /// 充值套餐列表
  Future<void> loadGoodsListData() async {
    try {
      var result = await GoodsDao.list();
      if (result.code == 0) {
        if (result.data != null) {
          var list = result.data!
              .where((element) =>
                  element.goodsType == PurchaseType.subscription.value)
              .toList();
          if (list.isNotEmpty) {
            if (GlobalConfig.pinnerSubIndex > list.length) {
              vip = list.first;
            } else if (GlobalConfig.pinnerSubIndex > 0) {
              vip = list[GlobalConfig.pinnerSubIndex - 1];
            }
          }
        } else {
          EasyLoading.showToast('获取充值套餐列表失败');
        }
      } else {
        EasyLoading.showToast(result.message);
      }
    } catch (e) {
      EasyLoading.showToast('网络错误');
    }
  }

  // 显示vip充值页
  Future<void> showVip() async {
    await loadGoodsListData();
    if (!isVip() && vip != null && GlobalConfig.monthvip_ios == 1) {
      Future.delayed(
          Duration(seconds: GlobalConfig.dealyShowVip_ios, milliseconds: 300),
          () {
        Get.put(SubscriptionOpenController());
        Get.dialog(
          const SubscriptionOpenPage(),
          barrierDismissible: false,
          useSafeArea: false,
        );
        // Get.toNamed(AppRoutes.monthPurchase);
      });
    }
  }

  // 显示举报页面
  Future<void> showReportView() async {
    if (GlobalConfig.showReportView == 1) {
      Future.delayed(Duration(seconds: GlobalConfig.reportViewDelay), () {
        Get.dialog(
          const ReportPage(),
          barrierDismissible: false,
          useSafeArea: false,
        );
      });
    }
  }

  Future<void> _loadAppConfig() async {
    try {
      // 刷新用户信息
      await UserinfoDao.updateCenter();

      var result = await AppDao.config();
      if (result.code == 0) {
        if (result.data != null) {
          var adDayLimit = JsonUtil.getObject<String>(
              result.data?.config, (v) => v['addaylimit']);
          var appController = Get.find<AppController>();
          appController.adDayLimit = int.parse(adDayLimit ?? '0');
          // 解析配置
          var config = json.decode(result.data!.config!);
          print("_loadAppConfig config is ${config}");
          if (config != null) {
            GlobalConfig.addaylimit = int.parse(config['addaylimit']);
            GlobalConfig.useragreement =
                config['useragreement'] ?? GlobalConfig.useragreement;
            GlobalConfig.privacy = config['privacy'] ?? GlobalConfig.privacy;
            GlobalConfig.customerPhone =
                config['customerPhone'] ?? GlobalConfig.customerPhone;
            GlobalConfig.customerWx =
                config['customerWx'] ?? GlobalConfig.customerWx;
            GlobalConfig.customerQQ =
                config['customerQQ'] ?? GlobalConfig.customerQQ;
            try {
              GlobalConfig.monthvip = int.parse(config['monthvip']);
            } catch (e) {
              print(e);
            }
            try {
              GlobalConfig.monthtips = int.parse(config['monthtips']);
            } catch (e) {
              print(e);
            }
            try {
              GlobalConfig.customerClick = int.parse(config['customerClick']);
            } catch (e) {
              print(e);
            }
            try {
              GlobalConfig.cancelVipType = int.parse(config['cancelVipType']);
            } catch (e) {
              print(e);
            } //needphone
            try {
              GlobalConfig.needphone = int.parse(config['needphone']);
            } catch (e) {
              print(e);
            } //
            try {
              GlobalConfig.dealyShowVip = int.parse(config['dealyShowVip']);
            } catch (e) {
              print(e);
            } //
            try {
              GlobalConfig.goodsType = int.parse(config['goodsType']);
            } catch (e) {
              print(e);
            } //
            try {
              GlobalConfig.defaultSelVip = int.parse(config['defaultSelVip']);
            } catch (e) {
              print(e);
            } //

            GlobalConfig.systemShare =
                config['systemShare'] ?? GlobalConfig.systemShare;
            try {
              GlobalConfig.isReview = int.parse(config['isReview']);
            } catch (e) {
              print(e);
            } //

            try {
              GlobalConfig.refreshLogin = int.parse(config['refreshLogin']);
            } catch (e) {
              print(e);
            } //

            try {
              GlobalConfig.swipeCountAd = int.parse(config['swipeCountAd']);
            } catch (e) {
              print(e);
            } //

            try {
              GlobalConfig.waterfallAdGap = int.parse(config['waterfallAdGap']);
            } catch (e) {
              print(e);
            } //
            try {
              GlobalConfig.waterfallPageSize =
                  int.parse(config['waterfallPageSize']);
            } catch (e) {
              print(e);
            } //
            try {
              GlobalConfig.homeTabIndex = int.parse(config['homeTabIndex']);
            } catch (e) {
              print(e);
            } //
            try {
              GlobalConfig.monthvip_ios = int.parse(config['monthvip_ios']);
            } catch (e) {
              print(e);
            } //
            try {
              GlobalConfig.monthtips_ios = int.parse(config['monthtips_ios']);
            } catch (e) {
              print(e);
            } //
            try {
              GlobalConfig.defaultSelVip_ios =
                  int.parse(config['defaultSelVip_ios']);
            } catch (e) {
              print(e);
            } //
            try {
              GlobalConfig.cancelVipType_ios =
                  int.parse(config['cancelVipType_ios']);
            } catch (e) {
              print(e);
            } //
            try {
              GlobalConfig.dealyShowVip_ios =
                  int.parse(config['dealyShowVip_ios']);
            } catch (e) {
              print(e);
            } //

            GlobalConfig.vipUseragreement =
                config['vipUseragreement'] ?? GlobalConfig.vipUseragreement;

            GlobalConfig.autoRenewPolicy =
                config['autoRenewPolicy'] ?? GlobalConfig.autoRenewPolicy;

            try {
              GlobalConfig.forceDisplayPromotion =
                  int.parse(config['forceDisplayPromotion']);
            } catch (e) {
              print(e);
            } //
            try {
              GlobalConfig.pinnerSubIndex = int.parse(config['pinnerSubIndex']);
            } catch (e) {
              print(e);
            } //
            try {
              GlobalConfig.showReportView = int.parse(config['showReportView']);
            } catch (e) {
              print(e);
            }
            try {
              GlobalConfig.reportViewDelay =
                  int.parse(config['reportViewDelay']);
            } catch (e) {
              print(e);
            }
          }
        }
      }
    } catch (e) {
      LogUtil.e(e);
    }
  }
}
